module.exports = (sequelize, DataTypes) => {
  const Tag = sequelize.define('Tag', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    name: {
      type: DataTypes.STRING(30),
      allowNull: false,
      validate: {
        len: [1, 30],
        notEmpty: true
      }
    },
    color: {
      type: DataTypes.STRING(7),
      defaultValue: '#87ceeb',
      validate: {
        is: /^#[0-9A-Fa-f]{6}$/i // 验证十六进制颜色值
      }
    }
  }, {
    tableName: 'tags',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: false, // 标签不需要更新时间
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [
      {
        fields: ['user_id']
      },
      {
        unique: true,
        fields: ['user_id', 'name'],
        name: 'unique_user_tag'
      }
    ]
  });

  Tag.associate = (models) => {
    // 标签属于用户
    Tag.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user',
      onDelete: 'CASCADE'
    });

    // 标签与日记多对多关联
    Tag.belongsToMany(models.Diary, {
      through: models.DiaryTag,
      foreignKey: 'tag_id',
      otherKey: 'diary_id',
      as: 'diaries',
      onDelete: 'CASCADE'
    });
  };

  return Tag;
}; 